package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.AntiDose;
import org.brisling.medical.domain.MedicalRecipel;
import org.brisling.medical.service.AntiDoseService;
import org.brisling.medical.service.RecipelService;
import org.brisling.sysman.domain.VOJobUser;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryAntidoseService</p>
 * <p>Description: 抗菌药物使用强度查询service</p>
 * <p>Company: tongking</p>
 * @author trastor
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午9:59:40
 */
@RestController
@RequestMapping("/antiDose/query")
public class QueryAntidoseService extends AbstractBaseQueryService<AntiDose>{
	
	
	@Autowired
	private AntiDoseService antiDoseService;
	
	@Autowired
	private QueryDictionaryService qryDictionaryService;
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;

	@Autowired
	private RecipelService qryService;
	
	@Autowired
	private QueryPermissionService qryPermissionService;
	
	public QueryAntidoseService(){
		this.moduleName = ConstSysParam.MODULE_ANTI_DOSE;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = AntiDose.class;
		typeMap = this.getTypeMap(clazz);
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_anti_dose/"+_page);
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<AntiDose> getListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){	
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}
			//查找科室数据		
		}
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<AntiDose> getDeptListDomain(@RequestBody(required=false) String body){		
		
		//获取所有前台传递参数
		Map<String,Object> map = this.getBodyParam(body);
		
		//获取当前登录用户identify
		String userid = shiroSecurityService.getCurrentUserIdentify();
		
		String dataType = "1";
		//判断是否超级管理部门
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
				dataType = "2";
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
				dataType = "3";
			}
			//查找科室数据
		}
		
		//获取前台传递的查询参数
		@SuppressWarnings("unchecked")
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		//判断并增加查询参数
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", dataType);		
		
		//将查询参数重新push到条件map中
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		
		//查询数据结果
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	
	private List<AntiDose> getList(String monitor_year_month){
		
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,monitor_year_month); 
		//查询表
		return super.getAllList(sql);
		
	}
	
	/**
	 * 查询实时数据
	 * @param body
	 * @return
	 */
	@RequestMapping("/getRealTimeListDomain.action")
	public ListDomain<AntiDose> getRealTimeListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> paramMap = this.getBodyParam(body);
		
		String[] monitorDate = super.getMonitorDate(paramMap);
		if(monitorDate!=null && monitorDate.length>1){			
			
			String start = monitorDate[0];
			String end = monitorDate[1];
			String year_month = monitorDate[2];
			List<AntiDose> inlists =countMedicalInpatient (year_month,start,end,null);
			
			
			if(inlists!=null ){				
				antiDoseService.save(inlists);
				return super.getListDomainByConditionAndOrderUseTable(body, typeMap, orderMap,true);
			}					
			
		}
		//查询表
		
		return new ListDomain<AntiDose>();
	}
	
	
	public void autoTask(Integer year,Integer month){
		this.autoMonitor(year, month);
		this.autoUpdateStandard(year, month);
	}
	/**
	 * 执行自动统计
	 */
	public void autoMonitor(Integer year,Integer month){
		
		
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		
		//分药品统计抗菌药物使用强度
//		qryAntiDrugdoseService.autoMonitor();
		
		List<AntiDose> inlists = countMedicalInpatient(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1],null);
		
		
		//查询已有数据
		List<AntiDose> oldLists = this.getList(yestodayMonth[2]);
		LinkedHashMap<String,AntiDose> lmap = new LinkedHashMap<String,AntiDose>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				AntiDose b = oldLists.get(i);
				String _key = null;
				if(b!=null && b.getDept_code()!=null){
					if(b.getDoct_code()==null ){
						_key = b.getDept_code().toString();
					}else{
						_key = b.getDept_code() +"-" + b.getDoct_code();
					}
					lmap.put(_key, b);
				}
			}
		}
		
		
		if(inlists!=null ){
			
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					AntiDose b = inlists.get(i);
					String _key = null;
					if(b!=null && b.getDept_code()!=null){
						if(b.getDoct_code()==null ){
							_key = b.getDept_code().toString();
						}else{
							_key = b.getDept_code() +"-" + b.getDoct_code();
						}
						if(lmap.containsKey(_key)){
							inlists.get(i).setId(lmap.get(_key).getId());
						}
					}
				}
			}
			
			antiDoseService.save(inlists);			
		}	
	}
	
	public void autoUpdateStandard(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		antiDoseService.updateStandard(yestodayMonth[2]);
	}
	/**
	 * 统计住院患者抗菌药物使用情况
	 * @param year_month
	 * @param startDate
	 * @param endDate
	 * @param countType	0,期间出院病人;1,期间在院病人
	 * @return
	 */
	public List<AntiDose> countMedicalInpatient(String year_month,String startDate ,String endDate,String countType){
		
		
		
		//出院病人统计语句
		String[] sqlids= {"anti_dose_all_inpatient","anti_dose_dept_inpatient","anti_dose_doct_inpatient"};
		
		//String[] sqlids= {"anti_dose_all_inpatient"};
		
		
		
		//统计全院数据-住院
		
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<AntiDose> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		return lists;
		
	}
	
	
	
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public AntiDose getOne(@RequestParam(value="id",required=false) Long id){
				
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public AntiDose getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	/**
	 * 自动插入
	 * @param AntiMedical
	 */

	
	public void autoInsertData(){
		List<AntiDose>  lists=getAntiDoseAbnormal();
		String Bizcode = qryPermissionService.getBizFlowConfig("recipel").getFullBizcode();
		String flowid = qryPermissionService.getBizFlowConfig("recipel").getFlowid();
		if(lists!=null){
			
			for(AntiDose a:lists){
				//System.out.println("\n--------------------------------got it----------------------------------");
				MedicalRecipel sendObj = new MedicalRecipel();
				sendObj.setId(null);
				sendObj.setInquiry_item("用药异常");
				sendObj.setInquiry_item_code("6");
				sendObj.setInquiry_item_sub("抗菌药物使用强度");
				sendObj.setDoct_depart_name(a.getDept_name());
				sendObj.setPatient_type("2");
				List<VOJobUser> jobUsr = SysConfig.getJobUserByDept("20", a.getDept_code().toString());
				sendObj.setDoct_name(jobUsr.get(0).getDoct_name());
				sendObj.setDoct_id(jobUsr.get(0).getDoct_code().toString());
				sendObj.setDeptid(a.getDept_code());
				sendObj.setInquiry_item_subcode("14");
				sendObj.setPatient_type("2");
				sendObj.setDoct_depart_code(a.getDept_code().toString());
				sendObj.setInquiry_date(new java.sql.Date(new java.util.Date().getTime()));
				sendObj.setInquiry_reason("抗菌药物使用强度异常, 请予以核实");
				sendObj.setFlowid(flowid);
				sendObj.setFullBizcode(Bizcode);
				//设置异常实体信息
				String id =SysConfig.getConfig("inquiryUserId");
				qryService.completeTask(id, sendObj);
			}
		}
	}
	
	/**
	 * 查询抗菌药物使用强度
	 * @return null
	 */
	public List<AntiDose> getAntiDoseAbnormal(){				
		String sql =qryDictionaryService.getSqlByBizcode("medical_anti_dose");		
		if(sql == null || sql.length() < 1){
			sql = "select * from medical_anti_medicals where data_type = 2 and ANTI_PERCENT is not null and AMOUNT_PERCENT_STANDARD is not null and anti_percent > amount_percent_standard and monitor_year_month = '%1$s'";
		}
		//sql = new String("select * from medical_anti_dose;");
		sql = String.format(sql, DateUtil.getYestodayMonthDay()[2]);
		
		try {
			return super.getClassedAllList(sql, AntiDose.class);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}

	public void getAllListByYearMonth(String yearMonth) {
		// TODO Auto-generated method stub
//		String sql = "select * from medical_anti_dose where monitoryearmonth = '" + yearMonth + "'";
		
	}	
	
}
